package com.guw.TestReflection;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

//通过反射获取泛型
public class Test03 {

    public void test1(Map<String, User> map, List<User> list) {
        System.out.println("test1");
    }

    public Map<String, User> test2() {
        System.out.println("test2");
        return null;
    }

    public static void main(String[] args) throws Exception {
        Method method = Test03.class.getMethod("test1", Map.class, List.class);

        //获得泛型的参数类型getGenericParameterTypes()
        Type[] genericParameterTypes = method.getGenericParameterTypes();
        for (Type genericParameterType : genericParameterTypes) {
            System.out.println(genericParameterType);
            //判断泛型的参数类型是否是结构化参数类型
            if (genericParameterType instanceof ParameterizedType) {
                //如果是,强转出来获得真实参数信息
                Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument);
                }
            }
        }
        //获得泛型的返回值类型
        Method method2 = Test03.class.getMethod("test2", null);
        //获得泛型的返回值类型的方法getGenericReturnType()
        Type genericParameterType = method2.getGenericReturnType();
        //判断泛型的参数类型是否是结构化参数类型
        if (genericParameterType instanceof ParameterizedType) {
            //如果是,强转出来获得真实参数信息
            Type[] actualTypeArguments = ((ParameterizedType) genericParameterType).getActualTypeArguments();
            for (Type actualTypeArgument : actualTypeArguments) {
                System.out.println(actualTypeArgument);
            }
        }
    }
}


